package cc.vv.party.service.impl;

import cc.vv.party.beans.model.*
import cc.vv.party.beans.vo.CommunityPartyCommitteeVO
import cc.vv.party.beans.vo.PartyCommitteeAdminVO
import cc.vv.party.beans.vo.PartyOrgMemberVO
import cc.vv.party.service.CommunityPartyCommitteeService;
import cc.vv.party.common.base.BaseServiceImpl;
import cc.vv.party.common.constants.StatusCode
import cc.vv.party.common.ext.uuid
import cc.vv.party.common.ext.wrapper
import cc.vv.party.common.wrapper.PageWrapper
import cc.vv.party.exception.BizException
import cc.vv.party.mapper.*
import cc.vv.party.param.CommunityPartyCommitteeEditParam
import com.baomidou.mybatisplus.mapper.EntityWrapper
import com.baomidou.mybatisplus.plugins.Page
import commonx.core.content.transfer
import commonx.core.content.transferEntries
import org.apache.commons.collections.CollectionUtils
import org.apache.commons.lang.StringUtils
import org.springframework.beans.factory.annotation.Autowired
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional
import kotlin.streams.toList

/**
 * <p>
 *  服务实现类
 * </p>
 *
 * @author Gyb
 * @since 2018-10-12
 */
@Service
open class CommunityPartyCommitteeServiceImpl : BaseServiceImpl<CommunityPartyCommitteeMapper, CommunityPartyCommittee>(), CommunityPartyCommitteeService {

    @Autowired
    lateinit var partyCommitteeAdminMapper: PartyCommitteeAdminRelationMapper

    @Autowired
    lateinit var partyCommitteeMemberMapper: PartyCommitteeOrgRelationMapper

    @Autowired
    lateinit var roleMapper: RoleMapper

    @Autowired
    lateinit var userRoleMapper: UserRoleMapper

    @Transactional(rollbackFor = [(Exception::class)])
    override fun edit(param: CommunityPartyCommitteeEditParam, userId: String): Boolean {
        var entity: CommunityPartyCommittee

        var role = roleMapper.getByType("committee")

        //社区大党委是否存在
        var exitEntity: CommunityPartyCommittee? = baseMapper.selectList(EntityWrapper<CommunityPartyCommittee>().eq("community", param.community)).firstOrNull()

        if(StringUtils.isBlank(param.id)){
            if(exitEntity != null){
                throw BizException(StatusCode.MESSAGE_EXIST.statusCode, "该社区已经存在社区大党委信息")
            }

            entity = param.transfer()
            entity.id = uuid()
            entity.createUser= userId
            super.insert(entity)
        } else {
            entity = super.selectById(param.id) ?: throw BizException(StatusCode.MESSAGE_NOT_EXIST)

            if(exitEntity != null && !exitEntity.id.equals(entity.id)){
                throw BizException(StatusCode.MESSAGE_EXIST.statusCode, "该社区已经存在社区大党委信息")
            }

            if(StringUtils.isNotBlank(param.street)) entity.street = param.street
            if(StringUtils.isNotBlank(param.community)) entity.community = param.community
            if(StringUtils.isNotBlank(param.partyCommitteeName)) entity.partyCommitteeName = param.partyCommitteeName
            if(StringUtils.isNotBlank(param.convener)) entity.convener = param.convener
            if(StringUtils.isNotBlank(param.responsibleUnit)) entity.responsibleUnit = param.responsibleUnit
            if(StringUtils.isNotBlank(param.principalName)) entity.principalName = param.principalName
            if(StringUtils.isNotBlank(param.principalAccount)) entity.principalAccount = param.principalAccount
            if(StringUtils.isNotBlank(param.partyCommitteeyIntroduction)) entity.partyCommitteeyIntroduction = param.partyCommitteeyIntroduction

            //删除成员信息
            partyCommitteeMemberMapper.delete(EntityWrapper<PartyCommitteeOrgRelation>().where("party_committeey_id = {0}", entity.id))

            //删除旧账号管理员权限信息
            var adminList = partyCommitteeAdminMapper.selectList(EntityWrapper<PartyCommitteeAdminRelation>().where("party_committeey_id = {0}", entity.id))
            if(CollectionUtils.isNotEmpty(adminList)){
                var accountList = adminList.stream().map { it.adminAccount }.toList()
                userRoleMapper.delete(EntityWrapper<UserRole>().eq("role_id", role.id).`in`("user_account", accountList))
            }

            //删除管理员信息
            partyCommitteeAdminMapper.delete(EntityWrapper<PartyCommitteeAdminRelation>().where("party_committeey_id = {0}", entity.id))
        }

        //保存组织成员信息
        if(CollectionUtils.isNotEmpty(param.memberList)){
            for(str in param.memberList!!){
                var temp = PartyCommitteeOrgRelation()
                temp.id = uuid()
                temp.partyCommitteeyId = entity.id
                temp.orgMemberId = str
                partyCommitteeMemberMapper.insert(temp)
            }
        }

        //保存管理员信息
        if(CollectionUtils.isNotEmpty(param.adminList)){
            for(temp in param.adminList!!){
                //新增管理员
                temp.id = uuid()
                temp.partyCommitteeyId = entity.id
                partyCommitteeAdminMapper.insert(temp.transfer())

                //新增管理员权限
                var admin = UserRole()
                admin.roleId = role.id
                admin.userAccount = temp.adminAccount
                admin.createUser = userId
                userRoleMapper.insert(admin)
            }
        }

        return true
    }

    @Transactional(rollbackFor = [(Exception::class)])
    override fun deleteCommunityPartyCommittee(id: String): Boolean {
        //删除成员信息
        partyCommitteeMemberMapper.delete(EntityWrapper<PartyCommitteeOrgRelation>().where("party_committeey_id = {0}", id))

        var role = roleMapper.getByType("committee")
        //删除旧账号管理员权限信息
        var adminList = partyCommitteeAdminMapper.selectList(EntityWrapper<PartyCommitteeAdminRelation>().where("party_committeey_id = {0}", id))
        if(CollectionUtils.isNotEmpty(adminList)){
            var accountList = adminList.stream().map { it.adminAccount }.toList()
            userRoleMapper.delete(EntityWrapper<UserRole>().eq("role_id", role.id).`in`("user_account", accountList))
        }

        //删除管理员信息
        partyCommitteeAdminMapper.delete(EntityWrapper<PartyCommitteeAdminRelation>().where("party_committeey_id = {0}", id))

        //删除党委信息
        return super.deleteById(id)
    }

    override fun getCurrentUserManagerPartyCommittee(account: String): CommunityPartyCommitteeVO {
        return baseMapper.getCurrentUserManagerPartyCommittee(account)
    }

    override fun info(id: String): CommunityPartyCommitteeVO {
        var communityParty = super.selectById(id) ?: throw BizException(StatusCode.MESSAGE_NOT_EXIST)
        var result = communityParty.transfer<CommunityPartyCommitteeVO>()

        var memberList = partyCommitteeMemberMapper.selectList(EntityWrapper<PartyCommitteeOrgRelation>().where("party_committeey_id = {0}", id))
        if(CollectionUtils.isNotEmpty(memberList)){
            result.memberList = memberList.transferEntries<PartyOrgMemberVO>() as ArrayList
        }

        var adminList = partyCommitteeAdminMapper.selectList(EntityWrapper<PartyCommitteeAdminRelation>().where("party_committeey_id = {0}", id))
        if(CollectionUtils.isNotEmpty(adminList)){
            result.adminList = adminList.transferEntries<PartyCommitteeAdminVO>() as ArrayList
        }

        return result
    }

    override fun listPage(street: String?, community: String?, name: String?, size: Int, page: Int): PageWrapper<CommunityPartyCommitteeVO> {
        var pages = Page<CommunityPartyCommitteeVO>(page, size)
        pages.records = baseMapper.selectListPage(pages, street, community, name)
        return pages.wrapper()
    }

}
